
# 权限管理相关视图
from django.http import HttpRequest, HttpResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import Permission
from LogisticsCard.models import Log


@login_required
def permissions_view(request: HttpRequest) -> HttpResponse:
    """
    权限列表视图，展示所有权限信息。
    :param request: HttpRequest对象
    :return: 渲染权限列表页面
    """
    permissions = Permission.objects.filter(delete_at__isnull=True)
    return render(request, 'permissions/index.html', {'permissions': permissions})


@login_required
def add_permission_view(request: HttpRequest) -> HttpResponse:
    """
    权限创建视图，处理权限表单提交。
    :param request: HttpRequest对象
    :return: 渲染权限创建页面或跳转到列表
    """
    if request.method == 'POST':
        name = request.POST.get('name')
        codename = request.POST.get('codename')
        if Permission.objects.filter(codename=codename).exists():
            return render(request, 'permissions/add.html', {'error': '标识已存在'})
        perm = Permission.objects.create(name=name, codename=codename, content_type_id=1)  # content_type_id需根据实际模型调整
        Log.objects.create(user=request.user, action='other', detail=f'添加权限:{name}({codename})')
        return redirect('/permissions/')
    return render(request, 'permissions/add.html')


@login_required
def edit_permission_view(request: HttpRequest, perm_id: int) -> HttpResponse:
    """
    权限编辑视图，处理权限编辑表单提交。
    :param request: HttpRequest对象
    :param perm_id: 权限ID
    :return: 渲染权限编辑页面或跳转到列表
    """
    perm = get_object_or_404(Permission, id=perm_id)
    if request.method == 'POST':
        old_name = perm.name
        old_codename = perm.codename
        perm.name = request.POST.get('name')
        perm.codename = request.POST.get('codename')
        perm.save()
        Log.objects.create(user=request.user, action='other', detail=f'编辑权限:{old_name}({old_codename}) -> {perm.name}({perm.codename})')
        return redirect('/permissions/')
    return render(request, 'permissions/edit.html', {'perm': perm})


@login_required
def delete_permission_view(request: HttpRequest, permission_id: int) -> HttpResponse:
    """
    权限删除视图，处理权限删除操作。
    :param request: HttpRequest对象
    :param permission_id: 权限ID
    :return: 跳转到权限列表页面
    """
    permission = get_object_or_404(Permission, id=permission_id)
    permission_name = permission.name
    permission.delete()
    Log.objects.create(user=request.user, action='other', detail=f'删除权限:{permission_name}')
    return redirect('/permissions/')
